package trader.currency.concurrent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import trader.util.Util;

public class Trader {
    public static final ArrayList<Currency> currencies = new ArrayList<Currency>();
    private static final String REPLACE_ME = "@@@";
    private static final String SEARCH_URL = "/search.php?market=CURRENCY&underlying=" + REPLACE_ME + "/SEK&instrument_type=MiniFuture";
    
    static {
        currencies.add(new Currency("DKK", new String[] {"DRX", "DRV", "DRS"}));
        currencies.add(new Currency("GBP", new String[] {"DQX", "DCK", "DCL", "KC5", "KC3", "EBF", "EBC"}));
        currencies.add(new Currency("NOK", new String[] {"DRU", "DRQ", "DRT", "Q2J", "Q2H", "Q2K"}));
        currencies.add(new Currency("USD", new String[] {"CU9", "HNN", "CCX", "RL1", "C1G", "C1H", "C03", "RL0", "K77", "K7D", "K78", "JM8", "NU6", "RL2"}));
        currencies.add(new Currency("EUR", new String[] {"CXP", "HKR", "CCV", "RL3", "C1J", "C1K", "G5L", "DVV", "K75", "K74", "EBB", "JM7", "RL4"}));
        currencies.add(new Currency("CHF", new String[] {"H5J", "H5H", "DQV", "SNR", "SNS", "SNU", "SNT"}));
    }
    
    public static void main(String[] args) {
        new Trader().run();
    }
    
    public void run() {
        if (!Util.login(Util.MAIL, Util.PASSWORD)) {
            System.out.println("Failed to login");
            return;
        }
    
        for (Currency curr : currencies) {
            for (String id : curr.ids) {
                //String data_key = getDataKey(curr.name);
                //if (data_key == null) {
                 //   continue;
                //}
                new Thread(new Poller(id, curr)).start();
            }
        }
        
        while (true) {
            if (Util.cashChanged.getAndSet(false)) {
                Util.atomicCash.set((long)getPortfolioCash(Util.buyPortfolio));
                System.out.println("Updating portfolio cash: " + Util.atomicCash);
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
    }
    
    private double getPortfolioCash(int portfolio) {
        URL url = null;
        try {
            url = new URL(Util.BASE_URL + "/portfolio_overview.php?port_id=" + portfolio);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Cookie", Util.sessionId);
            String line = "";
            String magic = "<td class=\"arial_11\" id=\"available_funds\" style=\"background-color:#FFFFFF; text-align:right\">";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = in.readLine()) != null) {
                line = line.trim();
                if (line.startsWith(magic)) {
                    return Double.parseDouble(line.substring(magic.length(), line.length() - 5));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
        return 0;
    }
    
    private String getDataKey(String name) {
        URL url = null;
        try {
            url = new URL(Util.BASE_URL + SEARCH_URL.replaceAll(REPLACE_ME, name));
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
        try {
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Cookie", Util.sessionId);
            String line = "";
            String magic = "option = { action: 'data_by_id', data_key: ";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = in.readLine()) != null) {
                line = line.trim();
                if (line.startsWith(magic)) {
                    in.close();
                    return line.substring(line.indexOf("'", magic.length()) + 1, line.lastIndexOf("'"));
                }
            }
            in.close();
        } catch (IOException e) {
            System.out.println("getDataKey() failed: " + name + " " + e);
        }
        return null;
    }
}
